package com.briup.web.controller;

import com.alibaba.excel.EasyExcel;
import com.briup.bean.DemoData;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/file")
public class FileController {
    @GetMapping("/download")
    public void download(HttpServletResponse response) throws Exception {
        //设置响应头：
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");//响应体数据格式
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        //响应体的内容默认是内联方式（浏览器视口区）attachment 以附件的方式进行下载，下载文件名就是 测试.xlsx
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        //将生成excel字节信息写出响应报文响应体
        OutputStream out = response.getOutputStream();
        //将service层返回值写入输出流
        EasyExcel.write(out, DemoData.class).sheet().doWrite(data());
    }
    public List<DemoData> data(){
        ArrayList<DemoData> list = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            //1.构造器
            //2.set方法 lombok 链式调用
            //3.builder
            DemoData data = new DemoData();
            data.setDate(new Date());
            data.setName("lisi");
            data.setDoubleData(200.00);
            list.add(data);
        }
        return list;
    }
}
